package com.tony.multipledatasource.dao.impl;

import com.tony.multipledatasource.dao.StudentDao;
import com.tony.multipledatasource.entity.Student;
import com.tony.multipledatasource.mapper.StudentMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by xuxia on 2024/4/8 00:25
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Resource
    @Qualifier(value = "mysqlJdbcTemplate")
    private JdbcTemplate mysqlJdbcTemplate;

    @Resource
    @Qualifier(value = "oracleJdbcTemplate")
    private JdbcTemplate oracleJdbcTemplate;


    @Override
    public List<Map<String, Object>> getAllStudentsMapByMySql() {
        return mysqlJdbcTemplate.queryForList("select * from student");
    }

    @Override
    public List<Map<String, Object>> getAllStudentsMapByOracle() {
        return oracleJdbcTemplate.queryForList("select * from student");
    }

    @Override
    public List<Student> getAllStudentsBeanByMySql() {
        return mysqlJdbcTemplate.query("select * from student",  new StudentMapper());
    }

    @Override
    public List<Student> getAllStudentsBeanByOracle() {
        return oracleJdbcTemplate.query("select * from student",  new StudentMapper());
    }

    @Override
    public Student getStudentBySnoWithMySql(String sno) {
        String sql = "select * from student where s_no = :s_no";
        Map<String, Object>  map = new HashMap<>();
        map.put("s_no", sno);
        MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(map);
        NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mysqlJdbcTemplate);
        List<Student> students = template.query(sql, sqlParameterSource, new StudentMapper());
        return CollectionUtils.isEmpty(students) ? null : students.get(0);
    }

    @Override
    public Student getStudentBySnoWithOracle(String sno) {
        String sql = "select * from student where s_no = :s_no";
        Map<String, Object>  map = new HashMap<>();
        map.put("s_no", sno);
        MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(map);
        NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(oracleJdbcTemplate);
        List<Student> students = template.query(sql, sqlParameterSource, new StudentMapper());
        return CollectionUtils.isEmpty(students) ? null : students.get(0);
    }
}
